/**
 *构造StructVO
 */ 
function getStructVO(){
	var obj = new StringBuffer(); 
	obj.append("{javaClass:'nc.vo.er.pub.QueryStructVO',");
	//设置查询对象
	obj.append("vetQryObj:" + $getQryObjsVector() + ",");
	//设置常用查询条件
	obj.append("voNormalCond:" + $getNormalCond() + ",");
	
	//设置单位信息
	obj.append("corp:" + $getCorp(true) + ",");
	//设置日期
	obj.append($getDate(true) + ",");
	//设置币种   
	obj.append("currPks:" + $$getCurrty(true) + ",");
	//设置复选框
	obj.append("djzt:'" + $getChecked() + "',");
	//设置权限控制vo
	obj.append("powerCtrlVO:" + $getPowerCtrlVO() + ",");
	//顶级查询对象
	obj.append("vetTopLevelQryObj:null,"); // + $getTopLevelQryObj() + ",");//顶级查询对象在后台生成
	//自定义查询条件sql(新查询模版只返回拼好的条件sql)
	obj.append("strCustomCondWhere:" + $getCustomCondWhere() + ",");
	//账页格式
//	obj.append("strBillType:'金额式'"); 
//	obj.append("isVouchshow:" +$getVouchshow()) 
	obj.append("}");
	return obj.toString();
}

function $getVouchshow(){
	return getComponent('isShow').getValue() == 'Y'? true : false;
}

/*设置公司*/
function $getCorp(isJsonStr){
	var ds = getDataset('queryFormDs');
	var row = ds.getSelectedRow();
	var value = row.getCellValue(ds.nameToIndex('mult_corp_code'));
	if(isJsonStr)
		return (value != null && value != '')? "[" + value + "]" : null;
	else{
			//返回公司名称
			value = getComponent('mult_corp_comp').getValue();
			//value = row.getCellValue(ds.nameToIndex('mult_corp_name'));
			return (value != null && value != '')?  value : null;
		}
}

/*设置日期、还是月份 【 资金账表以外的账表按单据日期查询 】*/
function $getDate(isJsonStr){
	var ds = getDataset('queryFormDs');
	var row = ds.getSelectedRow();
	var itemValue = row.getCellValue(ds.nameToIndex('querytype_combo'));
	var flag = false;
	if(itemValue == 'date'){
		var startDate = row.getCellValue(ds.nameToIndex('startdate'));
		var endDate = row.getCellValue(ds.nameToIndex('enddate'));
		flag = false;
	}else if(itemValue == 'month'){
		var startDate = row.getCellValue(ds.nameToIndex('start_ref_name'));
		var endDate = row.getCellValue(ds.nameToIndex('end_ref_name'));
		flag = true;
	}
	if(isJsonStr){
		return "querybyPeriod:" + flag + "," + "date:['" + startDate + "','" + endDate + "']"
	}
	else 
		return startDate + webbx_trans('BxContrastPageModel_000004') + endDate;
}

/*设置复选框*/
function $getChecked(){
	var ds = getDataset('queryFormDs');
	var row = ds.getSelectedRow();
	//str += "m_bBillStat:" + row.getCellValue(ds.nameToIndex(''));
	var sel_djzt = row.getCellValue(ds.nameToIndex('djzt_combo'));
	var djzt = -10000;
	if (sel_djzt == 0) {
		// 全部
		djzt = -10000;
	} else if (sel_djzt == 1) {
		// 已保存
		djzt = 1;
	} else if (sel_djzt == 2) {
		// 已审核
		djzt = 2;
	} else if (sel_djzt == 3) {
		// 已生效
		djzt = 10;
	}
	return djzt;
}

/*设置权限控制vo*/
function $getPowerCtrlVO(){
	var	obj = "{javaClass:'nc.vo.er.pub.PowerCtrlVO',";
		/* 添加单位信息，单位信息必须在其他条件中的第一位 */
		obj += "userId:'" + getPkUser() + "',";
		obj += "pk_corp:" + $getCorp(true) + "}";
	return obj;
}

/**设置顶级查询对象*/
function $getTopLevelQryObj(){
	var vet = new StringBuffer("{javaClass:'java.util.Vector',list:[");
	var arr = $$getQueryObjs(); 
	for(var i = 0,len = arr.length; i<len; i++){
		var v = arr[i]; 
		vet.append("{javaClass:'nc.vo.er.newreport.TopLevelQryObj',");
		if(v[1] == null || v[1] == 'undefined')
			vet.append("pk_type:null,");
		else
			vet.append("pk_type:'" + v[1] + "',");//查询对象类型标识
		vet.append("typeName:null,");
		if(v[4] == 'Y')
			vet.append("includeSub:true,");//是否包含下级
		else
			vet.append("includeSub:false,");//是否包含下级
//		vet.append("accEle:false,");//是否小计元素
		vet.append("valueRange:null");//取值范围
		vet.append("}");
		if(i != arr[i].length-1)
			vet.append(",");
	}
	vet.append("]}");
	return vet.toString();
}

/*设置查询对象Vector数组*/
function $getQryObjsVector(){ 
	var gridDs = getDataset('queryTemplateDs');
	var count = gridDs.getRowCount();
	if(count == 0)
		return null;
	var vet = new StringBuffer("{javaClass:'java.util.Vector',list:[");
	for(var i = 0; i < count; i++){
		var row = gridDs.getRow(i);
		if(row.getCellValue(0) == null || row.getCellValue(0) == '-1')
			continue;
		vet.append($getQryObj(row));
		if(i != count - 1)
			vet.append(",");
	}
	vet.append("]}");
	return vet.toString();
}

/*设置QryCondArrayVO数组,全部是五个元素的数组*/
function $getNormalCond(){
	//得到查询对象来组成QryCondArrayVO[0]
	var	normalCond = new StringBuffer();
	var arr = $$getQueryObjs();
	if(arr != null){
	 	normalCond.append("[{javaClass:'nc.vo.arap.pub.QryCondArrayVO',");
	 	normalCond.append("logicAnd:true,");//boolean
	 	normalCond.append("items:" + $getQryCondVO(arr));//数组
	 	normalCond.append("},");
	}
	//得到区分客户供应商的条件、QryCondArrayVO[1] TODO?

	//增加应收范围 TODO?
	//如果币种输入不为空（全部币种），则添加币种条件
	var currArr = eval($$getCurrty(true));
	if(currArr != null){
		normalCond.append("{javaClass:'nc.vo.arap.pub.QryCondArrayVO',");
		normalCond.append("logicAnd:false,");
		normalCond.append("items:");
				normalCond.append("[{javaClass:'nc.vo.arap.pub.QryCondVO',");
				normalCond.append("fldorigin:'fb',");
				normalCond.append("qryfld:'bzbm',");
				normalCond.append("boolopr:'=',");
				normalCond.append("value:'" + currArr + "',");
				normalCond.append("fldtype:0");
				normalCond.append("}]");
		normalCond.append("},");
	}
	normalCond.append("{javaClass:'nc.vo.arap.pub.QryCondArrayVO',");
	normalCond.append("logicAnd:false,");
	normalCond.append("items:");
		normalCond.append("[{javaClass:'nc.vo.arap.pub.QryCondVO',");
		normalCond.append("fldorigin:'djlxda',");
		normalCond.append("qryfld:'isloan',");
		normalCond.append("boolopr:'=',");
		normalCond.append("value:'Y',");
		normalCond.append("fldtype:0");
		normalCond.append("}]");
	normalCond.append("}");

	normalCond.append("]");
	return normalCond.toString();
}

/******************************/

/*获取币种的条件，没有则返回NULL*/
//TODO
function $$getCurrty(isJsonStr){
	var formDs= getDataset('queryFormDs');
	var curr_value = formDs.getSelectedRow().getCellValue(formDs.nameToIndex('pk_currtype'));
	if(curr_value != null && curr_value != ''){
		if(isJsonStr)
			return "['" + curr_value + "']";
		else
			return curr_value;
	}
	else 
		return null;
}
/*获取查询对象，没有则返回NULL,返回数组 ['对象id','对象值pk','code','name','是否合计']*/
function $$getQueryObjs(){
	var gridDs = getDataset('queryTemplateDs');
	var gridCount = gridDs.getRowCount();
	var arr = new Array();
	for(var i=0; i < gridCount; i++){
		
		var row = gridDs.getRow(i);
		var fldIndex = gridDs.nameToIndex("queryObj");
		var pkIndex = gridDs.nameToIndex("pk");
		var codeIndex = gridDs.nameToIndex("code");
		var nameIndex = gridDs.nameToIndex("name");
		var isSubIndex =  gridDs.nameToIndex("isSub");
		var otherInfoIndex = gridDs.nameToIndex("otherInfo");
		var value = row.getCellValue(0);
		if(value != null && value != '-1'){
			var str = [row.getCellValue(fldIndex),row.getCellValue(pkIndex),row.getCellValue(codeIndex),
			           row.getCellValue(isSubIndex),row.getCellValue(nameIndex),row.getCellValue(otherInfoIndex)];
			arr.push(str);
		}
	}
	if(arr.length != 0)
		return arr;
	else 
		return null;
}

/*构造QryCondVO*,传入二维数组，与这个VO对应*/
function $getQryCondVO(arr){
	var obj = new StringBuffer("[");
	for(var i=0,len = arr.length; i<len; i++){
		var v = arr[i];
		obj.append("{javaClass:'nc.vo.arap.pub.QryCondVO',");
		obj.append("qryfld:'" + v[5] + "." + v[0] + "',");
		obj.append("fldorigin:null,");
		
		obj.append("fldtype:1,");
		obj.append("boolopr:' is not ',");
		obj.append("objValues:'null'}");
		if(v[1] != null){
			obj.append(",{javaClass:'nc.vo.arap.pub.QryCondVO',");
			obj.append("qryfld:'" + v[5] + "." + v[0] + "',");
			obj.append("fldorigin:null,");
			obj.append("fldtype:0,");
			obj.append("boolopr:' in ', ");
			obj.append("objValues:{javaClass:'java.util.ArrayList',list:['" + v[1] + "']}}");
		}
		if(i != arr.length-1) obj.append(",");
		else  obj.append("]")
	}
	return obj.toString();
}

/**构造查询对象VO*/
function $getQryObj(row){
	var ds = getDataset('queryTemplateDs');
	var obj = new StringBuffer("{javaClass:'nc.vo.arap.pub.QryObjVO',");
	obj.append("fldorigin:'" + row.getCellValue(ds.nameToIndex('otherInfo')) + "',");
	var issub = row.getCellValue(ds.nameToIndex('isSub'));
	obj.append("isSum:'" + issub + "',");
//	if(issub == 'Y'){
//		obj.append("isBhxj:true,");
//	}
//	else
//		obj.append("isBhxj:false,");
	//obj.append("fldtype:" + $$getInteger() + ",");

	var qryFld = row.getCellValue(ds.nameToIndex('queryObj'));
	if(qryFld != null)
		obj.append("qryfld:'" + qryFld +"',");
	else 
		obj.append("qryfld:null,");
	var objName = row.getCellValue(ds.nameToIndex('name'));
	if(objName != null)
		obj.append("strDisplayName:'" + objName +"',");
	else 
		obj.append("strDisplayName:null,");
	
	var pkvalue = row.getCellValue(ds.nameToIndex('pk'));
	if(pkvalue != null)
		obj.append("pk_bdinfo:'" + pkvalue +"'");//此处传的是参照的pk值（实际应该是 增加基本档案类型主键、这里用作后台做转换）
	else{
		obj.append("pk_bdinfo:null");
	}
	obj.append("}");
	return obj.toString();
}
/***获取UFBoolean*/
function $$getUFBoolean(value){
	var clazz = "{javaClass:'nc.vo.pub.lang.UFBoolean',value:";
	if(value == 'Y' || value == 'y')
		clazz += "true";
	else
		clazz += "false";
	return  clazz + "}";
}

/***获取Integer*/
function $$getInteger(value){
	return "{javaClass:'java.lang.Integer',value:" + value + "}";
}

/*点击确定*/
function doConfirm(){
	var ds = getDataset('queryTemplateDs');
	var pDs = parent.getDataset('bodyDataset');
	if(!$checkQueryObjNotNull()){
		showMessageDialog(webbx_trans('yer_reportqry004'));
		return;
	}
	if(!$checkDateNotNull()){
		return ;
	}
	if($checkQueryObj()){
		showMessageDialog(webbx_trans('yer_reportqry001'));
		return;
	}
	
	var map = new HashMap();
	var nameIndex = ds.nameToIndex('name');
	var objIndex = ds.nameToIndex('queryObj');
	var queryArr = ['jkbxr','deptid','szxmid','fydeptid','fydwbm'];
	var queryArrMap = new HashMap();
	for(var i=0; i<queryArr.length; i++)
		queryArrMap.put(queryArr[i],i);
	var mapstr = '';
	for(var i=0; i < ds.getRowCount(); i++){
		var row = ds.getRow(i);
		var value = row.getCellValue(objIndex);
		if(value != null && value != '' && value != '-1'){
			var index = queryArrMap.get(value);
			var name = row.getCellValue(nameIndex);
			if(name == null || name == '')
				name = webbx_trans('yer_reportqry_all');
			map.put('qryobj'+index,name);
			mapstr += 'qryobj'+index + ":" + name;
			if(i != ds.getRowCount()-1)
				mapstr += "$";
		}
	}
	 
	var corpCode = $getCorp(false);
	if(corpCode.indexOf(',') != -1){
		map.put('corpcode','corpcode');
		mapstr += "corpcode:corpcode";
	}
	/*设置 公司、帐页格式、日期*/
	var otherMap = new HashMap();
	var otherMapStr = '';
	otherMap.put('headcorp',$getCorp(false));
	otherMapStr += 'headcorp' + ":" + $getCorp(false)+"$";
	otherMap.put('headdate',$getDate(false));
	otherMapStr += 'headdate' + ":" + $getDate(false)+"$";
	var zygs = 0;
	var jtbwb = parent.getSessionAttribute("jtbwb");
	var currentBz = $$getCurrty(false);
	if(currentBz == null || currentBz == '' || currentBz == jtbwb) 
		zygs = 0;//'ZYGS_JE'
	else 
		zygs = 1;//'ZYGS_WBJE';
		
	otherMap.put('booktype',zygs);
	otherMapStr += 'booktype' + ":" + zygs;
	
	var structVo = getStructVO();
	if(typeof parent.saveQryCondition != 'undefined'){
		parent.saveQryCondition(structVo,mapstr,otherMapStr,true);
	}
	parent.repaintForm(map,otherMap);
	
	var param = "report_query_param=" + encodeURIComponent(structVo);
	var loader = new DatasetLoader(pDs);
	loader.setKeyValue(Dataset.MASTER_KEY);
	loader.setLoadParam(param);
	loader.load(parent);
	parent.hideDialog('query_dialog',false);
}

function getStrSize(s){
	var charCode,tlength = 0;
	for(i=0,len=s.length; i<len; i++){
		charCode = s.charCodeAt(i);
		if(charCode < 0x007f){
			tlength = tlength + 1;
		}else if((0x0080 <= charCode)&&(charCode <= 0x07ff))
			tlength += 2;
		else if((0x0080 <= charCode)&&(charCode <= 0xffff))
			tlength += 3;
	}
	return tlength;
}

/**设置自定义查询条件sql(新查询模版只返回拼好的条件sql)*/
function $getCustomCondWhere(){
	//返回固定条件
	var fixConDs = getDataset('fixConDs');
	var len = fixConDs.getRowCount();
	if(fixConDs != null && len != 0){
		var condition = '';; 
		for(var i=0; i<len; i++){
			var fixrow = fixConDs.getRow(i);
			var key = fixrow.getCellValue(0);
			if( i!= 0)
				condition += " and ";
			if(fixrow.getCellValue(6) == 'in'){
				var v = fixrow.getCellValue(2);
				var arr = v.split(",");
				var arr2 = new Array();
				for(var k=0; k<arr.length; k++){
					arr2.push("$" + arr[k] + "$");
				}
				condition += key + " in (" + arr2.join(",") + ")";	
			}
			else
				condition += key + " = $" + fixrow.getCellValue(2) + "$";	
		}
		return "'"+condition+"'";			
	}
	return null;
} 


/*校验查询对象是否重复*/
function $checkQueryObj(){
	var ds = getDataset('queryTemplateDs');
	var queryObjsIndex = ds.nameToIndex('queryObj');
	var map = new HashMap();
	var count = 0;
	for(var k=0,len = ds.getRowCount(); k < len; k++){
		var row = ds.getRow(k);
		var v1 = row.getCellValue(queryObjsIndex);
		if(v1 != null && v1 != '-1'){
			count++;
			map.put(v1,k);
		}
	}
	return (count != map.size())? true : false
}
/*判空查询对象至少得有一个*/
function $checkQueryObjNotNull(){
	var ds = getDataset('queryTemplateDs');
	var queryObjsIndex = ds.nameToIndex('queryObj');
	var flag = false;
	for(var k=0,len = ds.getRowCount(); k < len; k++){
		var row = ds.getRow(k);
		var v1 = row.getCellValue(queryObjsIndex);
		if(v1 != null && v1 != '-1'){
			flag = true;
			break;
		}
	}
	return flag;
}

function $checkDateNotNull(){
	var ds = getDataset('queryFormDs');
	var row = ds.getSelectedRow();
	var itemValue = row.getCellValue(ds.nameToIndex('querytype_combo'));
	if(itemValue == 'date'){
		var startDate = row.getCellValue(ds.nameToIndex('startdate'));
		if(startDate == null || startDate.trim() == ''){
			showMessageDialog(webbx_trans('yer_reportqry002'));
			return false;
		}
		var endDate = row.getCellValue(ds.nameToIndex('enddate'));
		if(endDate == null || endDate.trim() == ''){
			showMessageDialog(webbx_trans('yer_reportqry003'));
			return false;
		}
		var a = new Date(startDate.replace(/\-/g,"/"));
		var b = new Date(endDate.replace(/\-/g,"/"));
		if(a > b){
			showMessageDialog(webbx_trans('yer_reportqry005'));
			return false;
		}
			
	}else if(itemValue == 'month'){
		var startDate = row.getCellValue(ds.nameToIndex('start_ref_name'));
		if(startDate == null || startDate.trim() == ''){
			showMessageDialog(webbx_trans('yer_reportqry002'));
			return false;
		}
		var endDate = row.getCellValue(ds.nameToIndex('end_ref_name'));
		if(endDate == null || endDate.trim() == ''){
			showMessageDialog(webbx_trans('yer_reportqry003'));
			return false;
		}
		var a = new Date(startDate.replace(/\-/g,"/") + "/01");
		var b = new Date(endDate.replace(/\-/g,"/") + "/01");
		if(a > b){
			showMessageDialog(webbx_trans('yer_reportqry005'));
			return false;
		}
	}
	return true;
}

